import web
import json
import os
import subprocess

urls = (
    '/', 'index',
    '/load', 'load',
    '/importJson', 'importJson',
    '/export', 'export',
    '/genModel', 'genModel',
)
# app = web.application(urls, globals())
render = web.template.render('')

class MyApplication(web.application):
    def run(self, port=8080, *middleware):
        func = self.wsgifunc(*middleware)
        return web.httpserver.runsimple(func, ('0.0.0.0', port))

class index:
    def GET(self):
        return render.vss()

class load:
    def GET(self):
        if os.path.exists('vsstree.json'):
            existfile = open(r"vsstree.json", "r", encoding='utf-8')
            return json.dumps(json.load(existfile))
        else:
            result = []
            file = open("vss_rel_3.1.1.json", "r", encoding='utf-8')
            data = json.load(file)
            assembleTree(data, result)
            newfile = open(r"vsstree.json", "w", encoding='utf-8')
            newfile.write(json.dumps(result))
            newfile.close()
            return json.dumps(result)

class export:
    def POST(self):
        data = str(web.data(), encoding="utf-8")
        uuidList = eval(data)
        file = open("vss_rel_3.1.1.json", "r", encoding='utf-8')
        vssdata = json.load(file)
        assembleCustomVss(vssdata, uuidList)
        newfile = open(r"static/vss_export.json", "w", encoding='utf-8')
        newfile.write(json.dumps(vssdata))
        newfile.close()
       
        # web.header('Content-Type','application/octet-stream')
        # web.header('Content-disposition', 'attachment; filename=vss_export.json')
        # return open("vss_export.json", 'rb').read()

class genModel:
    def POST(self):
        data = str(web.data(), encoding="utf-8")
        uuidList = eval(data)
        file = open("vss_rel_3.1.1.json", "r", encoding='utf-8')
        vssdata = json.load(file)
        assembleCustomVss(vssdata, uuidList)
        newfile = open(r"static/vss_export.json", "w", encoding='utf-8')
        newfile.write(json.dumps(vssdata))
        newfile.close()
        # 要执行的命令
        command = "sudo rm -rf /home/sc/workspace/vehicle-app-python-template/gen/vehicle_model && sudo python3 /home/sc/vehicle-model-generator/gen_vehicle_model.py -T /home/sc/workspace/vehicle-app-python-template/gen/vehicle_model static/vss_export.json"
        process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        process.wait()
        print(process.stdout.read())
        return process.stdout.read()

class importJson:
    def POST(self):
        data = web.input(myfile={})
        dictData = json.loads(data['myfile'].value)
        result = []
        assembleTree(dictData, result)
        return json.dumps(result)

def assembleCustomVss(data, uuidList):
    if len(uuidList)>0:
        for key in list(data.keys()):
            desc = data[key]
            if desc["uuid"] in uuidList:  
                uuidList.remove(desc["uuid"])
                if "children" in desc:
                    assembleCustomVss(desc["children"], uuidList)
            else:
                data.pop(key)
        

def assembleTree(data, result):
     for key in data:
        temp = {}
        temp["id"]=data[key]["uuid"]
        temp["a_attr"]={"type":data[key].get("type"),"description":data[key].get("description"),"datatype":data[key].get("datatype")}
        temp["text"]=key
        if "children" in data[key]:
            temp["children"]=[]
            assembleTree(data[key]["children"], temp["children"])
        result.append(temp)

if __name__ == "__main__":
    app = MyApplication(urls ,globals())
    app.run(port=8082)
